<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\model\User as UserModel;
use app\common\controller\Backend;
use Exception;
use think\Request;

class User extends Backend
{
    //用户列表
    public function index()
    {
        $newsList = UserModel::select();
        return $this->fetch('user/index', ['userList' => $newsList]);
    }

    //用户编辑
    public function edit(Request $request)
    {
        $news = UserModel::findOrEmpty($request->get('id', 0));
        return $this->fetch('user/edit', [
            'user' => $news
        ]);
    }

    //用户删除
    public function delete(Request $request)
    {
        try {
            UserModel::destroy($request->get('id'));
        } catch (\Exception $e) {
            $this->error('删除失败');
        }

        $this->success('删除成功');
    }

    //用户保存
    public function save(Request $request)
    {
        try {
            $data = $request->post();

            if (!empty($data['password'])) {
                $data['password'] = password($data['password']);
            } else {
                unset($data['password']);
            }

            if (empty($data['id'])) {
                $where['username'] = strip_tags(trim($data['username']));
                $user = UserModel::where($where)->find();
                if (!empty($user)) {
                    throw new Exception("用户名已存在");
                }
                UserModel::create($data);
            } else {
                $where['username'] = strip_tags(trim($data['username']));
                $user = UserModel::where($where)->find();
                if (!empty($user) && $user->id != $data['id']) {
                    throw new Exception("用户名已存在");
                }
                UserModel::update($data);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->redirect('index');
    }
}
